<?php

namespace App\Console\Commands\Traits;

use GuzzleHttp\Client;
use Maatwebsite\Excel\Facades\Excel;

trait ExcelCommandTrait
{
    private array $excelCommandData = [];

    protected bool $inputExcel = true;

    public function setInputExcel(bool $inputExcel): self
    {
        $this->inputExcel = $inputExcel;
        return $this;
    }

    /**
     * 通用excel导入
     *
     * @param string $toCollectionClass
     * @param string $defaultUrl
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function excelImport(string $toCollectionClass, string $defaultUrl = ''): void
    {
        ini_set('memory_limit', '2048M');

        $url = $defaultUrl;
        if ($this->inputExcel) {
            $url = $this->ask('请输入excel地址  ');
            if (!$url) {
                dd('url不能为空');
            }
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.',
                $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        $import = Excel::toCollection(null, $savePath);

        // 删除文件
        @unlink($savePath);

        $obj = new $toCollectionClass;

        if ($this->excelCommandData) {
            $obj = $obj->setCommandData($this->excelCommandData);
        }

        $obj->collection($import, $this);
    }

    public function setExcelCommandData(array $data): self
    {
        $this->excelCommandData = $data;

        return $this;
    }
}
